package leetcode;


import java.util.*;

/**
 * 字符串解码
 */
public class LeetCode394 {
    public String decodeString(String s) {
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != ']') {
                stack.push(chars[i]);
                continue;
            }
            StringBuilder repeat = new StringBuilder();
            while (stack.peek() != '[') {
                repeat.insert(0, stack.pop());
            }
            stack.pop();
            StringBuilder count = new StringBuilder();
            while (!stack.isEmpty() && stack.peek() >= '0' && stack.peek() <= '9') {
                count.insert(0, stack.pop());
            }
            int cnt = Integer.parseInt(count.toString());
            for (int j = 0; j < cnt; j++) {
                for (int k = 0; k < repeat.length(); k++) {
                    stack.push(repeat.charAt(k));
                }
            }
        }
        StringBuilder result = new StringBuilder();
        while (!stack.isEmpty()) result.insert(0, stack.pop());
        return result.toString();
    }


    public static void main(String[] args) {
        LeetCode394 leetCode394 = new LeetCode394();
        System.out.println(leetCode394.decodeString("abc10[cd10[ab]]xyz"));
    }
}